<template>
  <div>
    <!-- 面包屑导航区 ---------------------------------------------------------->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 ------------------------------------------------------------>
    <el-card>
      <!-- 提示框 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        show-icon
        type="warning"
        :closable="false"
      ></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类级联选择框 -->
          <el-cascader
            class="cate_select"
            clearable
            v-model="selectedCats"
            :options="cateList"
            :props="cateProps"
            @change="handleCateChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- Tabs 页签区域 -->
      <el-tabs v-model="tabActiveName" @tab-click="onTabClick">
        <!-- Tab-1 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="dialogVisible = true"
          >
            添加参数
          </el-button>

          <!-- 动态参数表格 -->
          <el-table :data="manyData" border stripe>
            <el-table-column type="expand">
              <!-- 展开行内容 -->
              <template slot-scope="scope">
                <el-tag
                  :key="item.attr_id"
                  closable
                  @close="onTagClosed(i, scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                >
                  {{ item }}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showTagInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              label="序号"
              type="index"
              width="64px"
            ></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="showEdit(scope.row)"
                  icon="el-icon-edit"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParam(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- Tab-2 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="dialogVisible = true"
          >
            添加属性
          </el-button>

          <!-- 静态属性表格 -->
          <el-table :data="onlyData" border stripe>
            <el-table-column type="expand">
              <!-- 展开行内容 -->
              <template slot-scope="scope">
                <el-tag
                  :key="item.attr_id"
                  closable
                  @close="onTagClosed(i, scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                >
                  {{ item }}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInputRef"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showTagInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              label="序号"
              type="index"
              width="64px"
            ></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParam(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="addParamTitle"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="140px"
      >
        <el-form-item :label="addParamTitle + '：'" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="editParamTitle"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="140px"
      >
        <el-form-item :label="editParamTitle + '：'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogClosed">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [], // 商品分类列表
      // 级联选择框
      selectedCats: [], // 选中的数据
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // Tabs
      tabActiveName: 'many',
      manyData: [],
      onlyData: [],

      // 添加属性/参数对话框
      dialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

      // 编辑属性/参数对话框
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getCatList()
  },

  computed: {
    isBtnDisabled () {
      if (this.selectedCats.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateId () {
      if (this.selectedCats.length === 3) {
        return this.selectedCats[2]
      } else {
        return null
      }
    },
    addParamTitle () {
      return this.tabActiveName === 'many' ? '添加动态参数' : '添加静态属性'
    },
    editParamTitle () {
      return this.tabActiveName === 'many' ? '编辑动态参数' : '编辑静态属性'
    }
  },

  methods: {
    async getCatList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类信息失败！')
      }
      this.cateList = res.data
    },

    handleCateChange () {
      this.getParamsData()
    },

    onTabClick () {
      this.getParamsData()
    },

    // 获取参数列表数据
    async getParamsData () {
      if (this.selectedCats.length !== 3) {
        this.selectedCats = []
        this.$message({
          message: '请选择第三级分类。',
          type: 'warning'
        })
        this.manyData = []
        this.onlyData = []
        return
      }
      // 发送请求，获取对应分类参数
      const {
        data: res
      } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.tabActiveName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败！')
      }

      // 动态标签数据
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制tag文本框的显示与隐藏
        item.inputVisible = false
        // tag 文本框输入的值
        item.inputValue = ''
      })

      if (this.tabActiveName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },

    // 添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
      this.dialogVisible = false
      this.getParamsData()
    },
    // 编辑对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
      this.getParamsData()
    },
    // 显示编辑对话框狂
    showEdit (row) {
      this.editDialogVisible = true
      this.editForm = row
    },

    // 发送添加参数请求
    addParams () {
      // validate
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('校验失败！')
        }
        // send post request
        const {
          data: res
        } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.tabActiveName
        })
        // check result
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.$message.success('添加参数成功！')
        this.dialogVisible = false
        this.getParamsData()
      })
    },

    // 发送编辑参数请求
    editParams () {
      // validate
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('校验失败！')
        }
        // send post request
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.tabActiveName
          }
        )
        // check result
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑参数失败！')
        }
        this.$message.success('编辑参数成功！')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },

    // 删除参数
    async removeParam (row) {
      const result = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      // 提交删除请求
      if (result !== 'confirm') {
        return this.$message.info('已取消删除。')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      )

      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败！')
      }

      this.$message.success('删除参数成功！')
      this.getParamsData()
    },

    // 标签关闭，删除 tag 项
    onTagClosed (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },

    // 保存 attr_vals
    async saveAttrVals (row) {
      // 发起请求，保存操作
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('更新属性值失败！')
        return
      }
      this.$message.success('更新属性值成功！')
    },

    // 动态标签方法
    showTagInput (row) {
      row.inputVisible = true
      // $nextTick() 方法，等待页面上元素重新渲染完毕，才调用回调函数中代码
      // 防止代码执行时，元素还没准备好。
      this.$nextTick((_) => {
        this.$refs.saveTagInputRef.$refs.input.focus()
      })
    },

    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求，保存操作
      this.saveAttrVals(row)
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.cate_select {
  width: 500px;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 100px;
}
</style>
